<?php
namespace app\know\controller;

use app\know\controller\AdminKnowBaseController;
use app\know\validate\QuestionContentValidate;
use app\know\validate\QuestionValidate;
use app\know\validate\QuestionOptionValidate;
use app\know\model\MaterialModel;
use app\know\model\QuestionContentModel;
use app\know\model\QuestionModel;
use app\know\model\SysConfigModel;
use app\know\model\QuestionOptionModel;
use think\facade\Db;
use think\Exception;

/**
 * Class AdminQuestionController 试题控制器
 * @package app\know\controller
 */
class AdminQuestionController extends AdminKnowBaseController
{
    /**
     * 试题管理
     * @adminMenu(
     *     'name'   => '试题管理',
     *     'parent' => 'know/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> false,
     *     'order'  => 35000,
     *     'icon'   => '',
     *     'remark' => '试题管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_question_index_view');

        if (!empty($content)) 
		{
            return $content;
        }
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $nav = $this->request->param('nav', 'list');

        $where = ['is_delete' => 0];
        $materials = MaterialModel::where($where)
                                    ->order('order_number', 'desc')
                                    ->select();
                                    
        $w = [
            ['is_delete', '=', 0],
            ['type', 'in', ['SUBJECT', 'GRADE' , 'QUESTION_TYPE' , 'STAR', 'FREQUENCY', 'TEXTBOOK_VOLUME']]
        ];
        $rows = SysConfigModel::where($w)->order('order_number', 'desc')->select();
        $subjects = [];
        $grades = [];
        $question_types = [];
        $stars = [];
        $volumes = [];
        $frequencies = [];
        
        foreach($rows as $k => $v) 
		{
			if ($v['type'] == 'SUBJECT') 
			{
				array_push($subjects, $v);
			} 
			else if ($v['type'] == 'GRADE') 
			{
				array_push($grades, $v);
			} 
			else if ($v['type'] == 'STAR') 
			{
				array_push($stars, $v);
			} 
			else if ($v['type'] == 'TEXTBOOK_VOLUME') 
			{
				array_push($volumes, $v);
			}
            else if ($v['type'] == 'QUESTION_TYPE') 
			{
				array_push($question_types, $v);
			}
            else if ($v['type'] == 'FREQUENCY') 
			{
				array_push($frequencies, $v);
			}
		}

		$this->assign('materials', $materials);
        $this->assign('material_uuid', $material_uuid);
        $this->assign('chapter_uuid', $chapter_uuid);
        $this->assign('nav', $nav);
        $this->assign('subjects', $subjects);
        $this->assign('grades', $grades);
        $this->assign('question_types', $question_types);
        $this->assign('volumes', $volumes);
        $this->assign('frequencies', $frequencies);
        $this->assign('stars', $stars);
        $this->assign('grade_code', '');
        $this->assign('subject_code', '');
        
        return $this->fetch();
    }

    public function list()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['a.is_delete' => 0, 'a.parent_uuid' => null ];
        if ($chapter_uuid)
        {
            $where['a.chapter_uuid'] = $chapter_uuid;
        }
        if ($material_uuid)
        {
            $where['a.material_uuid'] = $material_uuid;
        }
        $model = new QuestionModel();

        $count = $model->where($where)
                    ->alias('a')
                    ->count();

        $rows = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_question_content b', 'a.uuid = b.question_uuid')
                    ->field('a.*, b.content, b.answer, b.text_analysis, b.remark')
                    ->page($pageNumber, $pageSize)
                    ->select();
        
        foreach ($rows as &$v)
        {
            $v['content'] = $this->htmlDecode($v['content']);
            $v['answer'] = $this->htmlDecode($v['answer']);
            $v['text_analysis'] = $this->htmlDecode($v['text_analysis']);
            $item = $this->getItemAction($v['id']);
            $v['option'] = $item ? $item['content']['option']: [];

            $children = [];
            if ($item)
            {
                foreach($item['children'] as $v1)
                {
                    $itm = [];
                    foreach($v1['content'] as $k3 => $v3)
                    {
                        $itm[$k3] = $v3;
                    }
                    foreach($v1['base'] as $k6 => $v6)
                    {
                        $itm[$k6] = $v6;
                    }
                    array_push($children, $itm);
                }
            }
            $v['children'] = $children;
        }
        $this->success('', null, ['rows' => $rows, 'total' => $count]);
    }
    
	public function add()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];
        
        Db::startTrans();
        try 
		{
            $this->addAction($param, null);
            Db::commit();
        } 
		catch (ValidateException $e) 
		{
            Db::rollback();
            $this->error($e->getError());
        }
        $this->success('添加成功');
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'Question.delete');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];
        $param['modify_datetime'] = date("Y-m-d H:i:s");
        
        Db::startTrans();
        try 
		{
            $ids = preg_split("/[\s;,]/", $id);
            $w[] = ['id', 'in', $ids];
            $w[] = ['is_delete' , '=', 0];
            $rows = QuestionModel::where($w)->select();
            if (empty($rows))
            {
                throw new Exception('试题不存在');
            }
            $uuids = [];
            foreach($rows as $v) 
            {
                array_push($uuids, $v['uuid']);
            }
            QuestionModel::where('uuid', 'in', $uuids)->save(['is_delete' => 1]);
            $this->opLog([
                'table_name' => (new QuestionModel())->getTableName(),
                'sql' => QuestionModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($id),
            ]);
            Db::commit();
        } 
		catch (\Throwable $th) 
		{
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
	public function edit()
    {
        $param = $this->request->param();
        
        Db::startTrans();
        try 
		{
            $this->editAction($param, null);
            Db::commit();
        } 
		catch (ValidateException $e) 
		{
            Db::rollback();
            $this->error($e->getError());
        }
        $this->success('修改成功');
    }

    public function maxOrder()
    {
        $order = QuestionModel::max('order_number');
        $this->success('', '', $order);
    }

    public function getItem()
    {
        $id = $this->request->param('id', '');
        $item = $this->getItemAction($id);
        $this->success('', null, $item);
    }

    public function getItemAction($id)
    {
        $model = new QuestionModel();
        return $model->getQuestion($id);
    }

    public function addAction($param, $parentParam)
    {
        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];
        
        $baseParams = $param['base'];
        $contentParams = $param['content'];

        $model = new QuestionModel();
        $baseParams['uuid'] = $model->getUUID();
        $baseParams['create_user'] = $user['user_login'];
        if (empty($parentParam) === false)
        {
            $baseParams['parent_uuid'] = $parentParam['uuid'];
        }
        $this->validateFailError($baseParams, 'Question.add');

        $row = QuestionModel::create($baseParams);
        if (empty($row)) 
        {
            throw new Exception('试题基本信息添加失败');
        }

        $contentParams['question_uuid'] = $baseParams['uuid'];
        $contentParams['subject_code'] = $baseParams['subject_code'];
        $contentParams['grade_code'] = $baseParams['grade_code'];
        if (empty($parentParam) === false)
        {
            $this->validateFailError($contentParams, 'QuestionContent.add');
        }
        else
        {
            $this->validateFailError($contentParams, 'QuestionContent.addChild');
        }
        $row = QuestionContentModel::create($contentParams);
        if (empty($row)) 
        {
            throw new Exception('试题信息添加失败');
        }
        $options = $contentParams['option']??[];
        foreach($options as $ko => $vo)
        {
            $vo['question_uuid'] = $baseParams['uuid'];
            $this->validateFailError($vo, 'QuestionOption.add');
            $row = QuestionOptionModel::create($vo);
            if (empty($row)) 
            {
                throw new Exception('试题选项信息添加失败');
            }
        }

        if ($baseParams['type_code'] === 'readAnalysis')
        {
            foreach($contentParams['children'] as $vc)
            {
                $this->addAction($vc, $baseParams);
            }
        }
    }
	
    public function editAction($param, $parentParam)
    {
        $baseParams = $param['base'];
        $contentParams = $param['content'];
        $id = $baseParams['id'];

        $user = $this->getAdminUser();
        $baseParams['modify_user'] = $user['user_login'];
        $baseParams['modify_datetime'] = date("Y-m-d H:i:s");
    
        $this->validateFailError($baseParams, 'Question.edit');
        $d = QuestionModel::where('id', $id)->find();
        
        $allowField = ['chapter_uuid', 
            'material_uuid', 'people', 'score', 'grade_code', 'subject_code', 'star_code', 
            'type_code', 'type_alias', 'difficulty_code', 'origin', 'order_number', 'is_delete',
            'is_enable', 'create_user', 'create_datetime', 'modify_user', 'modify_datetime'];
        QuestionModel::update($baseParams, ['id' => $id], $allowField);
        $this->opLog([
            'table_name' => (new QuestionModel())->getTableName(),
            'sql' => QuestionModel::getLastSql(),
            'create_user' => $user['user_login'],
            'before_data' => json_encode($d),
        ]);

        $d0 = QuestionContentModel::where('question_uuid', $d['uuid'])->find();
        $contentParams['id'] = $d0['id'];
        $contentParams['subject_code'] = $baseParams['subject_code'];
        $contentParams['grade_code'] = $baseParams['grade_code'];
        $this->validateFailError($contentParams, 'QuestionContent.edit');
        
        $optionsSave = $contentParams['option']??[];
        QuestionContentModel::update($contentParams, ['id' => $d0['id']], ['content', 'answer', 'text_analysis', 'video_analysis', 'remark']);
        $this->opLog([
            'table_name' => (new QuestionContentModel())->getTableName(),
            'sql' => QuestionContentModel::getLastSql(),
            'create_user' => $user['user_login'],
            'before_data' => json_encode($d0),
        ]);

        // 试题选项
        $options = QuestionOptionModel::where('question_uuid', $d['uuid'])->select();
        $s = count($options) - count($optionsSave);
        $delIds = [];
        $optionsSize = count($options);
        for($i = 0; $i < $s; $i++)
        {
            $di = $optionsSize - 1 - $i;
            $op = $options[$di];
            array_push($delIds, $op['id']);
            unset($di);
        }
        if (count($delIds) > 0)
        {
            QuestionOptionModel::where('id', 'in', $delIds)->delete();
        }

        foreach($optionsSave as $ko => $vo)
        {
            $vo['question_uuid'] = $d['uuid'];
            if (empty($options[$ko]) === false)
            {
                $vo['id'] = $options[$ko]['id'];
            }
            if (empty($vo['id']))
            {
                $this->validateFailError($vo, 'QuestionOption.add');
                $row = QuestionOptionModel::create($vo);
                if (empty($row)) 
                {
                    throw new Exception('试题选项信息添加失败');
                }
            }
            else
            {
                $this->validateFailError($vo, 'QuestionOption.edit');
                QuestionOptionModel::update($vo, ['id' => $vo['id']], ['content', 'label']);
            }
        }
        // 试题选项

        if ($baseParams['type_code'] === 'readAnalysis' && empty($contentParams['children']) === false)
        {
            foreach($contentParams['children'] as $vc)
            {
                $this->editAction($vc, $baseParams);
            }
        }

    }


}
